from flask import Blueprint, request, jsonify
from app.extensions import db
from app.models.user import User
from app.models.point_record import PointRecord  # 使用你已有的模型
from app.utils import JwtToken
from datetime import datetime

points_bp = Blueprint("points_bp", __name__)


# 1. 添加积分
@points_bp.route("/api/add-points", methods=["POST"])
def add_points():
    # 从请求头获取 token 并解析 openid
    auth_header = request.headers.get("Authorization", None)
    if not auth_header or not auth_header.startswith("Bearer "):
        return jsonify({'code': 401, 'msg': '缺少或无效的 token'}), 401

    token = auth_header.split(" ")[1]
    payload, verify_status = JwtToken.parse_token(token)
    if not verify_status or "openid" not in payload:
        return jsonify({'code': 401, 'msg': 'token 无效或过期'}), 401

    openid = payload["openid"]
    user = User.get_user_by_openid(openid)
    if not user:
        return jsonify({'code': 404, 'msg': '用户不存在'}), 404

    # 处理业务逻辑
    data = request.get_json()
    type_ = data.get("type")
    points = data.get("points")

    if not type_:
        return jsonify({'code': 400, 'msg': '缺少必要字段 type'}), 400

    # 如果是签到逻辑
    if type_ == "sign":
        today = datetime.utcnow().date()
        signed_record = PointRecord.query.filter_by(user_id=user.id, type="sign") \
            .filter(db.func.date(PointRecord.created_at) == today).first()

        if signed_record:
            # 已签到，不再加分
            return jsonify({
                'code': 200,
                'msg': '今天已签到',
                'data': {
                    "id": signed_record.id,
                    'issigned': True,
                    "user_id": signed_record.user_id,
                    "points": signed_record.points,
                    "type": signed_record.type,
                    "created_at": signed_record.created_at.strftime("%Y-%m-%d %H:%M:%S")
                }
            })

        # 第一次签到，默认给 50 分
        points = 50

    # 普通情况，必须传 points
    elif points is None:
        return jsonify({'code': 400, 'msg': '缺少必要字段 points'}), 400

    # 保存积分记录
    record = PointRecord(user_id=user.id, points=points, type=type_)
    db.session.add(record)
    db.session.commit()

    return jsonify({
        'code': 200,
        'msg': '积分添加成功',
        'data': {
            "id": record.id,
            'issigned': not (type_ == "sign"),  # 如果是签到，则返回 signed=True
            "user_id": record.user_id,
            "points": record.points,
            "type": record.type,
            "created_at": record.created_at.strftime("%Y-%m-%d %H:%M:%S")
        }
    })


# 2. 查询积分记录
@points_bp.route("/api/get-points", methods=["GET"])
def get_points():
    # token 解析
    auth_header = request.headers.get("Authorization", None)
    if not auth_header or not auth_header.startswith("Bearer "):
        return jsonify({'code': 401, 'msg': '缺少或无效的 token'}), 401

    token = auth_header.split(" ")[1]
    payload, verify_status = JwtToken.parse_token(token)
    if not verify_status or "openid" not in payload:
        return jsonify({'code': 401, 'msg': 'token 无效或过期'}), 401

    openid = payload["openid"]
    user = User.get_user_by_openid(openid)
    if not user:
        return jsonify({'code': 404, 'msg': '用户不存在'}), 404

    # 查询积分记录
    records = PointRecord.query.filter_by(user_id=user.id).order_by(PointRecord.created_at.desc()).all()
    total = db.session.query(db.func.sum(PointRecord.points)).filter_by(user_id=user.id).scalar() or 0
    return jsonify({
        'code': 200,
        'msg': 'success',
        'data':{ 'total_points': total,
            "points_list": [{
            "id": r.id,
            "user_id": r.user_id,
            "points": r.points,
            "type": r.type,
            "created_at": r.created_at.strftime("%Y-%m-%d %H:%M:%S")
            } for r in records]
        }
    })